// 按规则自动修复角色的未分配/总属性点与当前等级不匹配的问题
// 规则：
// - 期望总点数 = lvl * 4
// - 实际总点数 = strength + constitution + intelligence + agility + availablePoints
// - 差额 delta = 期望 - 实际
//   - delta > 0：补到 availablePoints
//   - delta < 0：优先从 availablePoints 回收，不足再按 力→体→智→敏 顺序回收，确保各项不为负

const mysql = require('mysql2/promise');
const config = require('./database-config.js');

async function main() {
    const conn = await mysql.createConnection(config.source);
    try {
        console.log('🔧 开始自动修复角色属性点...');

        const [rows] = await conn.execute(
            `SELECT c.id, c.name, c.lvl,
              ap.id AS apId, ap.strength, ap.constitution, ap.intelligence, ap.agility, ap.availablePoints
         FROM characters c
    LEFT JOIN character_attribute_points ap ON ap.characterId = c.id`
        );

        if (!rows || rows.length === 0) {
            console.log('✅ 没有角色数据');
            return;
        }

        let fixed = 0;
        for (const r of rows) {
            const lvl = r.lvl || 0;
            const expectedTotal = lvl * 4;
            let strength = r.strength || 0;
            let constitution = r.constitution || 0;
            let intelligence = r.intelligence || 0;
            let agility = r.agility || 0;
            let availablePoints = r.availablePoints || 0;

            const actualTotal = strength + constitution + intelligence + agility + availablePoints;
            const delta = expectedTotal - actualTotal;

            if (delta === 0) continue; // 无需修复

            // 若 ap 不存在，先创建空记录
            if (!r.apId) {
                await conn.execute(
                    `INSERT INTO character_attribute_points (characterId, strength, constitution, intelligence, agility, availablePoints, created_at, updated_at)
           VALUES (?, 0, 0, 0, 0, 0, NOW(), NOW())`,
                    [r.id]
                );
                strength = 0; constitution = 0; intelligence = 0; agility = 0; availablePoints = 0;
            }

            let newStrength = strength;
            let newConstitution = constitution;
            let newIntelligence = intelligence;
            let newAgility = agility;
            let newAvailable = availablePoints;

            if (delta > 0) {
                // 补到未分配
                newAvailable += delta;
            } else {
                // 回收多余
                let need = -delta;
                const takeAvail = Math.min(newAvailable, need);
                newAvailable -= takeAvail;
                need -= takeAvail;

                const order = [
                    ['strength', () => newStrength, (v) => (newStrength = v)],
                    ['constitution', () => newConstitution, (v) => (newConstitution = v)],
                    ['intelligence', () => newIntelligence, (v) => (newIntelligence = v)],
                    ['agility', () => newAgility, (v) => (newAgility = v)],
                ];

                for (const [, getter, setter] of order) {
                    if (need <= 0) break;
                    const cur = getter();
                    if (cur <= 0) continue;
                    const take = Math.min(cur, need);
                    setter(cur - take);
                    need -= take;
                }
                if (need > 0) {
                    console.warn(`⚠️ 角色ID=${r.id} 回收不足，仍剩余 ${need} 未回收（已尽量回收，不会为负）`);
                }
            }

            await conn.execute(
                `UPDATE character_attribute_points
            SET strength=?, constitution=?, intelligence=?, agility=?, availablePoints=?, updated_at=NOW()
          WHERE characterId = ?`,
                [newStrength, newConstitution, newIntelligence, newAgility, newAvailable, r.id]
            );

            fixed += 1;
            console.log(`➡️  修复角色ID=${r.id}, 等级=${lvl}: total ${actualTotal} -> ${expectedTotal}; ` +
                `四维(${strength},${constitution},${intelligence},${agility})/p=${availablePoints} -> ` +
                `(${newStrength},${newConstitution},${newIntelligence},${newAgility})/p=${newAvailable}`);
        }

        console.log(`✅ 属性点修复完成，修复 ${fixed} 条记录。`);
    } catch (e) {
        console.error('❌ 修复失败:', e.message || e);
        process.exitCode = 1;
    } finally {
        // @ts-ignore
        await conn.end();
    }
}

if (require.main === module) {
    main();
}


